package com.coai.twin.service

import org.influxdb.dto.Point
import org.springframework.stereotype.Service
import java.util.concurrent.TimeUnit

/**
 * 指标计算引擎 - 实时计算200+业务指标
 */
@Service
class MetricsCalculator(
    private val influxDBService: InfluxDBService
) {
    
    fun calculateMetrics(event: BusinessEvent) {
        when (event.eventType) {
            "MESSAGE_SENT" -> calculateMessageMetrics(event)
            "FILE_UPLOADED" -> calculateFileMetrics(event)
            "CALL_INITIATED" -> calculateCallMetrics(event)
            "INBOUND_ORDER_CREATED" -> calculateWarehouseMetrics(event)
            else -> calculateGenericMetrics(event)
        }
    }
    
    private fun calculateMessageMetrics(event: BusinessEvent) {
        // 消息类指标
        writeMetric("message_count", 1.0, event.source)
        writeMetric("message_total", 1.0, "total")
        
        // 响应时间指标
        event.data["responseTime"]?.let {
            writeMetric("message_response_time", it as Double, event.source)
        }
    }
    
    private fun calculateFileMetrics(event: BusinessEvent) {
        // 文件类指标
        val fileSize = event.data["fileSize"] as? Long ?: 0L
        writeMetric("file_count", 1.0, event.source)
        writeMetric("file_storage_used", fileSize.toDouble(), event.source)
    }
    
    private fun calculateCallMetrics(event: BusinessEvent) {
        // 通话类指标
        writeMetric("call_count", 1.0, event.source)
        
        val duration = event.data["duration"] as? Long ?: 0L
        writeMetric("call_total_duration", duration.toDouble(), event.source)
    }
    
    private fun calculateWarehouseMetrics(event: BusinessEvent) {
        // 仓储类指标
        writeMetric("warehouse_order_count", 1.0, event.source)
        
        event.data["estimatedDistance"]?.let {
            writeMetric("warehouse_total_distance", it as Double, event.source)
        }
    }
    
    private fun calculateGenericMetrics(event: BusinessEvent) {
        writeMetric("event_count", 1.0, event.eventType)
    }
    
    private fun writeMetric(measurement: String, value: Double, tag: String) {
        val point = Point.measurement(measurement)
            .time(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
            .addField("value", value)
            .tag("source", tag)
            .build()
        
        influxDBService.write(point)
    }
}
